<?php

namespace Home\Controller;

use Think\Controller;

class ShowController extends Controller {
	private $access_token='';
	public function demo() {
		// 设置选项，包括URL
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . appid . "&redirect_uri=http://nuower.com/index.php/Show/oauth&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
		header("Location:".$url);
	}
	
	public function oauth() {
		if (isset ( $_GET ['code'] )) {
			$code = $_GET ['code'];
			$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . appid . "&secret=" . appsecret . "&code=" . $code . "&grant_type=authorization_code";
			$output = https_request ( $url );
			// 第二步
			if (isset ( $output )) {
				$jsoninfo = json_decode ( $output, true );
				session(array('expire'=>$jsoninfo['expires_in']));
				session('token',$jsoninfo['access_token']);
				$url_info = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $jsoninfo ['access_token'] . "&openid=" . appid . "&lang=zh_CN";
				$userInfo = https_request ( $url_info );
			} else {
				$this->error ( "不好意思,出错了" );
			}
			// 第三步
			if (isset ( $userInfo )) {
				$res = json_decode ( $userInfo, true );
				cookie( "openid", $res ['openid'] );
				cookie( "nickname", $res ['nickname'] );
				$this->display ( "Show/index" );
			} else {
				$this->error ( "不好意思,出错了" );
			}
		} else {
			$this->error ( "不好意思,出错了" );
		}
	}
	public function index() {
		$data = F ( 'data' );
		if (empty ( $data )) {
			$data = M ( 'swf_area' )->select ();
			$cache = F ( 'data', $data );
			$this->assign ( "city", $cache );
		} else {
			// dump($data);
			$this->assign ( "city", $data );
		}
		$this->display ();
	}
	// 订单不需要搬运
	public function order() {
		header ( "Content-type: text/html; charset=utf-8" );
		// 解释下参数: 参数1---目标邮箱, 参数2----邮件标题,参数三--邮件正文,参数四---发件人名称;
		$data = I ();
		// dump($data);
		$data ['orderno'] = $this->orderNum ();
		$data ['ctime'] = date ( 'Y-m-d H:i:s' );
		$data ['openid'] = $_COOKIE['openid'];
		session("name",$data ['name']);
		session("orderno",$data ['orderno']);
		$time = $data ['appTime'];
		$date = $data ['appDate'];
		// 模板
		$data ['time'] = $data ['appDate'] . $data ['appTime'];
		unset ( $data ['appTime'] );
		unset ( $data ['appDate'] );
		$res = M ( 'order' )->data ( $data )->add ();
		 
		if ($res) {
			// 如果发送邮件推送成功并把信息保存到数据库并显示给用户
			$tpl = "订购单号:<span style='color:red'>" . $data ['orderno'] . "</span><br>下单时间:<span style='color:red'>" . $data ['ctime'] . "</span><br>收到来自<span style='color:red'>" . $data ["getCity"] . "</span>的订单<br>" . "联系人:<span style='color:red'>" . $data ['name'] . "</span><br>联系电话:<span style='color:red'>" . $data ['mphone'] . "</span><br>收货人电话:<span style='color:red'>" . $data ['yphone'] . "</span><br>" . "起始地：<br><span style='color:red'>" . $data ['startAdd'] . "</span><br>目的地：<br><span style='color:red'>" . $data ['endAdd'] . "</span><br>" . "搬家时间:<br><span style='color:red'>" . $time . " " . $date . "</span><br>" . "选择车型:<br><span style='color:red'>" . $data ['car'] . "</span><br>" . "总金额为:<br><span style='color:red'>" . $data ['cost'] . "</span>";

			$orderinfo=M('order')->find($res);

			
			if (SendMail ( 'wxd1277@163.com', '亲，又来新订单了！！', $tpl )) {
			
			} else {
				$this->error ( '订单失败了' );
			}
			$this->assign ( "orderinfo", $orderinfo );
			$this->display ( "detail" );
		} else {
			$this->error ( "订单失败了" );
		}
		
	}
	// 取消订单
	public function delOrder() {
		$data ['openid'] = $_SESSION ['openid'];
		$name = $_SESSION['name'];
		$ordNo = $_SESSION['orderno'];
		$tpl = $name."(".$_SESSION['nickname'].")"."取消订单了"."单号为:". $ordNo;
		 
		$where = array (
				"openid" => $data ['openid'] ,
				"orderno" => $ordNo
		);
		//0代表以删除订单
		$status['status'] = '-1';
		$res = M ( 'order' )->where ( $where )->save($status);; // 删除用户数据
		if ($res) {
			if (SendMail ( 'nuowoer@163.com', '亲，有人取消订单了！', $tpl )) {
				$this->success("取消订单！",U ( 'Show/index' ));
			} else {
				$this->error ( "取消订单失败",U ( 'Show/index' ) );
			}
		} else {
			$this->error ( "取消订单失败",U ( 'Show/index' ) );
		}
	}
	// 单号
	public function orderNum() {
		$data = date ( 'Ymd' );
		$whe = "%" . $data . '%';
		$where ['orderno'] = array (
				'like',
				$whe 
		);
		$res = M ( 'order' )->where ( $where )->order ( 'id desc' )->getField ( 'orderno' );
		// 如果存在
		if ($res) {
			$order = substr ( $res, - 4 ) + 1;
			$orderNo = 'E' . $data . sprintf ( "%04d", $order ); // 生成4位数，不足前面补0
		} else {
			// 否则单号就是0001
			$orderNo = 'E' . $data . "0001";
		}
		return $orderNo;
	}
	
	// 不需要搬运的 计算车费
	public function info() {
		header ( "Content-type: text/html; charset=utf-8" );
		$dst = $_POST ['dst'];

		// $domain = substr(strstr($dst, "分钟"),6);
		//$res = substr ( $dst, 0, strlen ( $dst ) - 6 );
		$car = $_POST ['car'];
		// 调用计算车费函数
		$Fc = $this->carCost ( $dst, $car );
		echo $Fc;
	}
	 
	/**
	 * *
	 * 车费计算公式
	 * $res距离,$car车型
	 *
	 * *
	 */
	private function carCost($res, $car) {

		switch ($car) {

			case "面包车" :

				// 起步价

				$Fa = 40;

				if ($res > 5) {

					$cost = round($Fa + ($res - 5) * 4);

				} else {

					$cost = $Fa;

				}

				break;

			case "小型平板货车" :

				// 起步价

				$Fa = 60;

				if ($res > 5) {

					$cost = round(60 + ($res - 5) * 5);

				} else {

					$cost = 60;

				}

				break;

			case "中型平板货车" :

				// 起步价

				$Fa = 85;

				if ($res > 5) {

					$cost = round($Fa + ($res - 5) * 5);

				} else {

					$cost = $Fa;

				}

				break;

			case "中型厢式货车" :

				// 起步价

				$Fa = 120;

				if ($res > 5) {

					$cost = round($Fa + ($res - 5) * 5);

				} else {

					$cost = $Fa;

				}

				break;

			default :

				// 起步价

				$Fa = 40;

				if ($res > 5) {

					$cost = round($Fa + ($res - 5) * 4);

				} else {

					$cost = $Fa;

				}

				break;

		}

		return $cost;

	}


	public function showadmin()
{	
	$id=I('get.id');
	$data=M('order')->find($id);
	$tpl = "订购单号:<span style='color:red'>" . $data ['orderno'] . "</span><br>下单时间:<span style='color:red'>" . $data ['ctime'] . "</span><br>联系人:<span style='color:red'>" . $data ['name'] . "</span><br>联系电话:<span style='color:red'>" . $data ['mphone'] . "</span><br>起始地：<br><span style='color:red'>" . $data ['startadd'] . "</span><br>目的地：<br><span style='color:red'>" . $data ['endadd'] . "</span><br>" . "搬家时间:<br><span style='color:red'>".$data ['time']."</span><br>" . "选择车型:<span style='color:red'>" . $data ['car'] . "</span><br>" . "物品详情:<span style='color:red'>" . $data ['items'] ."</span><br>备注:<span style='color:red'>" . $data ['备注']."</span><br>总金额为:<span style='color:red'>" . $data ['cost'] . "</span>";
$this->assign('tpl',$tpl);
	$this->display();
}


public function submit_order()
{
	$id=I('post.id');
	if (empty($id)) {
		$this->error('缺少参数');
	}else{
	$data['id']=$id;
	$data['status']=1;
	M('order')->save($data);
	$this->sendtpl_msg('oB_KewRQprjKA4ETYbqcRQgMiBk0',$id,'管理员，你好，有一个顾客预约了您的服务，请注意安排时间。');
	$this->sendtpl_msg('oB_KewXjx0kMThvx12moge3K9n8k',$id,'管理员，你好，有一个顾客预约了您的服务，请注意安排时间。');
	$this->success('提交成功。等待反馈',U('Show/index'));
	}
	
	
}


	//发送模板消息
	public function sendtpl_msg($touser,$id,$first=''){

    		$this->access_token=$this->getToken();

	$orderinfo=M('order')->find($id);
	$orderno=$orderinfo['orderno'];
	$cost=$orderinfo['cost'];



//模板消息	
$template=array(
'touser'=>$touser,
'template_id'=>"85vh2nUY5d0pGOYKdnqnY3_AjIWf8PO9c-RZSCWORUM",
'url'=>"http://nuower.com/index.php/show/showadmin/id/".$id,
'topcolor'=>"#7B68EE",
'data'=>array(
'first'=>array('value'=>urlencode($first),'color'=>"#743A3A"),
'keyword1'=>array('value'=>urlencode($orderinfo['name']),'color'=>'#743A3A'),
'keyword2'=>array('value'=>urlencode($orderinfo['mphone']),'color'=>'#743A3A'),
'keyword3'=>array('value'=>urlencode('小型搬家不需要搬运'),'color'=>'#743A3A'),
'keyword4'=>array('value'=>urlencode($orderinfo['time']),'color'=>'#743A3A'),
'keyword5'=>array('value'=>urlencode($orderinfo['items']),'color'=>'#743A3A'),
'remark'=>array('value'=>urlencode('请及时审核'),'color'=>'#743A3A'),
)
);

$cus_user=$orderinfo['openid'];

	$content='挪窝儿已经收到您的预约，正在努力匹配靠谱搬家师傅，请耐心等待。需要查看或取消订单，请点击“我的”>“我的订单”。
《相关费用说明》
1.报价不包含搬运费，现场如需搬运请与师傅协商价格。
2.报价不包含过路过桥费，面包车走海底隧道加收费用20元，货车走跨海大桥加收费用150元。
3.请在师傅到达之前完成打包，因客户原因导致司机等待的，按照20元/15分钟收取等待费。
4..搬家路线及里程以高德地图提供的两地最短行车距离为准。';

$data = '{
        "touser":"'.$cus_user.'",
        "msgtype":"text",
        "text":
        {
             "content":"'.$content.'"
        }
    }';


$json_template=json_encode($template);

$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;
$url2 = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->access_token;
$res=http_request($url,urldecode($json_template));
$res2=https_post($url2,urldecode($data));

}




public function saveorder()
	{
		$orderid=I('get.id');
		$map['id']=$orderid;
		$save['paystatus']=1;
		$save['paytype']='wx';
		$q=M('order')->where($map)->save($save);
		$this->sendtpl_msg('oB_KewRQprjKA4ETYbqcRQgMiBk0',$orderid,'小型搬家不需要搬运订单已支付');
		$this->sendtpl_msg('oB_KewXjx0kMThvx12moge3K9n8k',$orderid,'小型搬家不需要搬运订单已支付');
		if ($q) {
			$this->redirect('Remind/success');
		}
	}


		//发送客服消息
function _reply_customer($touser,$content){
	$ACC_TOKEN=$this->getToken();
    //$ACC_TOKEN=$this->getToken();
    $data = '{
        "touser":"'.$touser.'",
        "msgtype":"text",
        "text":
        {
             "content":"'.$content.'"
        }
    }';
    
    $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$ACC_TOKEN;
    
    $result = https_post($url,$data);
    $final = json_decode($result);
    return $final;
}

public function getToken()
{	
	$data = json_decode(get_php_file("access_token.php"));
    if ($data->expire_time < time()) {
       $json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".appid."&secret=".appsecret);
$access_token=json_decode($json_token,true);
//获得access_token
$f_access_token=$access_token['access_token'];
      if ($f_access_token) {
        $data->expire_time = time() + 7000;
        $data->access_token = $f_access_token;
      set_php_file("access_token.php", json_encode($data));
      }
    } else {

     $f_access_token = $data->access_token;
    }
    return $f_access_token;
	
}





}

?>